package com.liyunc.demo.config;

import com.liyunc.demo.model.entity.GoodsEntity;
import com.liyunc.demo.model.repository.GoodsRepository;
import com.liyunc.demo.service.impl.CacheServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author liyuncong
 * @version 1.0
 * @file DynamicScheduleTask
 * @brief DynamicScheduleTask
 * @details DynamicScheduleTask
 * @date 2022/4/17
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                        NAME               DESCRIPTION
 * 2022/4/17                   liyuncong          Created
 */

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class DynamicScheduleTask {

    @Autowired
    private CacheServiceImpl service;
    @Autowired
    private GoodsRepository goodsRepository;

    @PostConstruct
    private void init() {
        //启动先加载数据库
        updateData();
    }

    //3.添加定时任务 每10分钟执行一次
    @Scheduled(cron = "0 */10 * * * ?")
    private void configureTasks() {
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
        updateData();
    }

    private void updateData() {
        //先将数更新到数据库
        Set<Map.Entry<Long, GoodsEntity>> entrySet = service.stockMap.entrySet();
        while (entrySet.iterator().hasNext()) {
            Map.Entry<Long, GoodsEntity> next = entrySet.iterator().next();
            goodsRepository.saveAndFlush(next.getValue());
        }
        List<GoodsEntity> all = goodsRepository.findAll();
        HashMap<Long, GoodsEntity> stockMap = new HashMap<>();
        for (GoodsEntity entity : all) {
            stockMap.put(entity.getId(), entity);
        }
        synchronized (DynamicScheduleTask.class) {
            service.stockMap = stockMap;
        }
    }
}
